﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ENG.TeachersDiary.Forms;
using ENG.TeachersDiary.Model;

namespace ENG.TeachersDiary
{
  public partial class FrmCreateSchoolYear : Form
  {
    public FrmCreateSchoolYear()
    {
      InitializeComponent();
    }

    private void txtSchoolYearTitle_TextChanged(object sender, EventArgs e)
    {
      btnOk.Enabled = txtSchoolYearTitle.Text.Trim().Length > 0;
    }

    private void chkUse_CheckedChanged(object sender, EventArgs e)
    {
      foreach (var fItem in groupBox1.Controls)
      {
        if (fItem != chkUse && fItem is Control)
          (fItem as Control).Enabled = chkUse.Enabled;
      } // foreach (var fItem in groupBox1.Controls)
    }

    private void FrmCreateSchoolYear_Load(object sender, EventArgs e)
    {
      var db = Common.DBConn;
      schoolYearBindingSource.DataSource =
        db.SchoolYears;
    }

    public Model.SchoolYear GenerateSchoolYear(DiaryDB relativeDB)
    {
      Model.SchoolYear ret = null;

      ret = new Model.SchoolYear();
      ret.Title = txtSchoolYearTitle.Text.Trim();

      foreach (var fItem in lstClasses.CheckedItems)
      {
        Model.Class c = fItem as Model.Class;
        Model.Class newC = new Model.Class();
        newC.SchoolYear = ret;

        if (chkAskForClassRename.Checked)
        {
          string newName = FrmInput.ShowDialog(
            Properties.Resources.Renaming,
            Properties.Resources.Class + " " + c.Title + " ==> " +
            Properties.Resources.EnterNewClassName,
            c.Title);

          if (string.IsNullOrEmpty(newName))
            newC.Title = c.Title;
          else
            newC.Title = newName;
        }
        else
          newC.Title = c.Title;

        relativeDB.Classes.InsertOnSubmit(newC);

        if (chkGenerateStudents.Checked)
          foreach (var xItem in c.Students)
          {
            Model.Student s = new Model.Student();
            s.Class = newC;
            s.Name = xItem.Name;
            s.Surname = xItem.Surname;
            s.IsVisible = xItem.IsVisible;

            relativeDB.Students.InsertOnSubmit(s);
          } // foreach (var xItem in c.Students)
      } // foreach (var fItem in lstClasses.CheckedItems)

      return ret;
    }
  }
}
